package leetcode.medium.limit50;

import leetcode.ListNode;

/**
 * @author liuyy
 * @className No2
 * @description TODO
 * @date 2019/10/29 15:38
 **/
public class No2 {
    public static void main(String[] args) {
        ListNode l1 = ListNode.createByArray(new int[]{1, 2, 3});
        ListNode l2 = ListNode.createByArray(new int[]{3, 4, 8});
        No2 no2 = new No2();
        ListNode addTwoNumbers = no2.addTwoNumbers(l1, l2);
        ListNode.print(addTwoNumbers);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode d = new ListNode(-1);
        ListNode p = d;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            int val = carry;
            if (l1 != null) {
                val += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                val += l2.val;
                l2 = l2.next;
            }
            carry = val / 10;
            val = val % 10;
            p.next = new ListNode(val);
            p = p.next;
        }
        return d.next;
    }
}


